package br.com.cast.exercicio6;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


import br.com.cast.exercicio5.Clientes;
import br.com.cast.exercicio5.ConnectionFactory;



public class ContasDAO {

	Connection conexao;
	
	public ContasDAO(){
		ConnectionFactory connectionFactory = new ConnectionFactory();
		conexao = connectionFactory.getConnection();
	}
	
	public List<Clientes> buscaClientes() throws SQLException{
		List<Clientes> listaClientes = new ArrayList<Clientes>();
		
		PreparedStatement pst = null;
		
		try {
			pst = conexao.prepareStatement("select * from clientes");
			pst.execute();
			
			
			ResultSet rs = pst.getResultSet();
			
			
			
			while(rs.next()){
				Calendar dataConvertida = Calendar.getInstance();
				dataConvertida.setTimeInMillis(rs.getDate("data_nascimento")
						.getTime());
				Calendar dataConvertida2 = Calendar.getInstance();
				dataConvertida2.setTimeInMillis(rs.getDate("data_cadastro")
						.getTime());
				Clientes c = new Clientes();
				c.setId(rs.getInt("id"));
				c.setNome(rs.getString("nome"));
				c.setDataCadastro(dataConvertida);
				c.setDataNascimento(dataConvertida2);
			
				
				adicionaContas(c);
				listaClientes.add(c);
			}
			
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally {
			pst.close();
		}
		
		return listaClientes;
		
	}
	
	private void adicionaContas(Clientes c) throws SQLException{
		
		PreparedStatement pst = null;
		
		try {
			
			pst = conexao.prepareStatement("select numero from contas where id_cliente = ?");
			
			pst.setInt(1, c.getId());
			pst.execute();
			
			ResultSet rs = pst.getResultSet();
			
			while(rs.next()){
			
				Contas co = new Contas();
				co.setConta(rs.getInt("numero"));
				c.addContas(co);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			pst.close();
		}
		
	}
}
